<template>
  <div class="panel-header">
    <div class="panel-title">
      <i class="panel-icon"></i>
      <span>业绩排行榜</span>
      <div class="refresh-indicator">
        <span class="refresh-text">{{ countdown }}s</span>
        <div class="refresh-circle" :style="{ background: `conic-gradient(#1eb1fc ${countdownPercent}%, transparent 0%)` }"></div>
      </div>
    </div>
    <div class="panel-controls">
      <el-select v-model="filterType" size="small" class="filter-select">
        <el-option label="设备效率" value="device" />
        <el-option label="人员效率" value="operator" />
        <el-option label="平均车速" value="speed" />
        <el-option label="班次计米" value="length" />
      </el-select>
    </div>
  </div>

  <div class="panel-body">
    <div class="ranking-list">
      <transition-group name="flip-list">
        <div
          v-for="(item, index) in sortedRankingData"
          :key="item.id"
          class="ranking-item"
          :class="{ 'top-three': index < 3 }"
        >
          <div class="rank-number" :class="`rank-${index + 1}`">{{ index + 1 }}</div>
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-details">
              <span class="item-operator">{{ item.operator }}</span>
              <span class="item-divider">|</span>
              <span class="item-shift">{{ item.shift }}</span>
            </div>
          </div>
          <div class="item-value-container">
            <div class="item-value">
              {{ formatValue(item[filterType]) }}
              <span class="value-unit">{{ getUnit() }}</span>
            </div>
            <div class="change-indicator">
              <transition name="fade">
                <span v-if="item.change > 0" class="icon-wrapper up-arrow">
                  <SvgIcon name="arrow-up" size="16" />
                </span>
                <span v-else-if="item.change < 0" class="icon-wrapper down-arrow">
                  <SvgIcon name="arrow-down" size="16" />
                </span>
                <span v-else class="icon-wrapper no-change">
                  <SvgIcon name="minus" size="16" />
                </span>
              </transition>
              <span
                class="change-value"
                :class="{
                  'increase': item.change > 0,
                  'decrease': item.change < 0,
                  'no-change': item.change === 0
                }"
              >
                {{ Math.abs(item.change).toFixed(1) }}%
              </span>
            </div>
          </div>

          <!-- 进度条 -->
          <div class="progress-bar-container">
            <div
              class="progress-bar"
              :style="{ width: `${getProgressPercentage(item[filterType])}%` }"
            ></div>
          </div>
        </div>
      </transition-group>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { SvgIcon } from '@/components/icons'
import api from '@/services/api'

export default {
  name: 'PerformanceRanking',
  components: {
    SvgIcon
  },
  props: {
    initialType: {
      type: String,
      default: 'device'
    }
  },
  setup(props) {
    const filterType = ref(props.initialType)
    const rankingData = ref([])
    const previousData = ref({})
    const countdown = ref(5)
    const refreshInterval = ref(null)
    const countdownInterval = ref(null)

    // 计算倒计时百分比
    const countdownPercent = computed(() => {
      return (countdown.value / 5) * 100
    })

    // 根据当前筛选类型排序数据
    const sortedRankingData = computed(() => {
      return [...rankingData.value].sort((a, b) => b[filterType.value] - a[filterType.value])
    })

    // 获取进度条百分比
    const getProgressPercentage = (value) => {
      if (rankingData.value.length === 0) return 0

      const maxValue = Math.max(...rankingData.value.map(item => item[filterType.value]))
      return (value / maxValue) * 100
    }

    // 格式化显示值
    const formatValue = (value) => {
      if (filterType.value === 'speed') {
        return value.toFixed(1)
      } else if (filterType.value === 'length') {
        return value.toFixed(0)
      }
      return value.toFixed(2)
    }

    // 获取单位
    const getUnit = () => {
      switch (filterType.value) {
        case 'device':
          return '%'
        case 'operator':
          return '%'
        case 'speed':
          return 'm/min'
        case 'length':
          return 'm'
        default:
          return ''
      }
    }

    // 获取排行榜数据
    const fetchRankingData = async () => {
      try {
        // 保存上一次的数据用于计算变化
        previousData.value = {}
        rankingData.value.forEach(item => {
          previousData.value[item.id] = { ...item }
        })

        // 从API获取最新数据
        const response = await api.getRealtimeStatus()
        const devices = response.data || []

        // 转换数据格式并计算变化百分比
        const newData = devices.map(device => {
          const prev = previousData.value[device.device_id]

          // 计算变化百分比
          let change = 0
          if (prev) {
            const oldValue = prev[filterType.value]
            const newValue = getDeviceValue(device, filterType.value)
            if (oldValue > 0) {
              change = ((newValue - oldValue) / oldValue) * 100
            }
          }

          return {
            id: device.device_id,
            name: device.name || `设备${device.device_id}`,
            operator: device.operator || '未分配',
            shift: device.shift_type || '未知班次',
            device: calculateDeviceEfficiency(device),
            operator: calculateOperatorEfficiency(device),
            speed: device.speed || 0,
            length: device.shift_length || 0,
            change: change
          }
        })

        rankingData.value = newData
      } catch (error) {
        console.error('获取排行榜数据失败:', error)
        // 如果API失败，使用模拟数据
        if (rankingData.value.length === 0) {
          generateMockData()
        }
      }
    }

    // 计算设备效率
    const calculateDeviceEfficiency = (device) => {
      // 这里可以根据实际业务逻辑计算设备效率
      // 示例: 运行时间 / 总时间
      return device.efficiency || (Math.random() * 30 + 70)
    }

    // 计算操作员效率
    const calculateOperatorEfficiency = (device) => {
      // 这里可以根据实际业务逻辑计算操作员效率
      return device.operator_efficiency || (Math.random() * 40 + 60)
    }

    // 获取设备的特定值
    const getDeviceValue = (device, type) => {
      switch (type) {
        case 'device':
          return calculateDeviceEfficiency(device)
        case 'operator':
          return calculateOperatorEfficiency(device)
        case 'speed':
          return device.speed || 0
        case 'length':
          return device.shift_length || 0
        default:
          return 0
      }
    }

    // 生成模拟数据（当API不可用时）
    const generateMockData = () => {
      const mockDevices = []

      for (let i = 1; i <= 6; i++) {
        const deviceId = `LINE00${i}`
        const prev = previousData.value[deviceId]

        // 基础值
        let deviceEff = Math.random() * 30 + 70
        let operatorEff = Math.random() * 40 + 60
        let speed = Math.random() * 100 + 50
        let length = Math.random() * 2000 + 1000

        // 如果有上一次的数据，基于它生成小的变化
        if (prev) {
          deviceEff = prev.device + (Math.random() * 6 - 3)
          operatorEff = prev.operator + (Math.random() * 6 - 3)
          speed = prev.speed + (Math.random() * 10 - 5)
          length = prev.length + (Math.random() * 100 - 50)
        }

        // 确保值在合理范围内
        deviceEff = Math.max(50, Math.min(100, deviceEff))
        operatorEff = Math.max(40, Math.min(100, operatorEff))
        speed = Math.max(30, Math.min(200, speed))
        length = Math.max(500, Math.min(5000, length))

        // 计算变化百分比
        let change = 0
        if (prev) {
          const oldValue = prev[filterType.value]
          const newValue = filterType.value === 'device' ? deviceEff :
                          filterType.value === 'operator' ? operatorEff :
                          filterType.value === 'speed' ? speed : length

          if (oldValue > 0) {
            change = ((newValue - oldValue) / oldValue) * 100
          }
        }

        mockDevices.push({
          id: deviceId,
          name: `生产线${i}号`,
          operator: `操作员${i}`,
          shift: i % 2 === 0 ? '早班' : '晚班',
          device: deviceEff,
          operator: operatorEff,
          speed: speed,
          length: length,
          change: change
        })
      }

      rankingData.value = mockDevices
      console.log('生成模拟排行榜数据:', rankingData.value)
    }

    // 立即生成初始数据
    generateMockData()

    // 开始倒计时
    const startCountdown = () => {
      countdown.value = 5

      if (countdownInterval.value) {
        clearInterval(countdownInterval.value)
      }

      countdownInterval.value = setInterval(() => {
        countdown.value -= 1
        if (countdown.value <= 0) {
          countdown.value = 5
        }
      }, 1000)
    }

    // 监听筛选类型变化，重新计算变化百分比
    watch(filterType, () => {
      if (rankingData.value.length > 0 && Object.keys(previousData.value).length > 0) {
        rankingData.value = rankingData.value.map(item => {
          const prev = previousData.value[item.id]
          let change = 0

          if (prev) {
            const oldValue = prev[filterType.value]
            const newValue = item[filterType.value]
            if (oldValue > 0) {
              change = ((newValue - oldValue) / oldValue) * 100
            }
          }

          return {
            ...item,
            change
          }
        })
      }
    })

    onMounted(() => {
      // 初始加载数据
      fetchRankingData()

      // 设置定时刷新
      refreshInterval.value = setInterval(() => {
        fetchRankingData()
      }, 5000)

      // 启动倒计时
      startCountdown()
    })

    onUnmounted(() => {
      // 清除定时器
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
      }

      if (countdownInterval.value) {
        clearInterval(countdownInterval.value)
      }
    })

    return {
      filterType,
      rankingData,
      sortedRankingData,
      countdown,
      countdownPercent,
      getProgressPercentage,
      formatValue,
      getUnit
    }
  }
}
</script>

<style scoped>
.panel-title {
  display: flex;
  align-items: center;
}

.panel-title span {
  margin-right: 10px;
  font-size: 16px;
  font-weight: bold;
}

.panel-body {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.refresh-indicator {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.refresh-text {
  font-size: 12px;
  color: #1eb1fc;
  margin-right: 5px;
}

.refresh-circle {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid #1eb1fc;
  position: relative;
  transform: rotate(-90deg);
}

.filter-container {
  display: flex;
  align-items: center;
}

.filter-select {
  width: 100px;
}

.ranking-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 5px;
  width: 100%;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  background: rgba(30, 177, 252, 0.1);
  border-radius: 4px;
  position: relative;
  transition: all 0.3s ease;
  overflow: hidden;
}

.ranking-item:hover {
  background: rgba(30, 177, 252, 0.2);
  transform: translateX(5px);
}

.top-three {
  background: linear-gradient(90deg, rgba(30, 177, 252, 0.2), rgba(30, 177, 252, 0.05));
  border-left: 3px solid #1eb1fc;
}

.rank-number {
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  margin-right: 12px;
  font-weight: bold;
  font-size: 14px;
}

.rank-1 {
  background: linear-gradient(135deg, #ffd700, #ff9d00);
  color: #000;
}

.rank-2 {
  background: linear-gradient(135deg, #c0c0c0, #e0e0e0);
  color: #000;
}

.rank-3 {
  background: linear-gradient(135deg, #cd7f32, #e6a972);
  color: #000;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 4px;
}

.item-details {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.item-operator {
  margin-right: 5px;
}

.item-divider {
  margin: 0 5px;
  color: rgba(255, 255, 255, 0.4);
}

.item-value-container {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 15px;
  min-width: 80px;
}

.item-value {
  font-size: 18px;
  font-weight: bold;
  color: #1eb1fc;
}

.value-unit {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-left: 2px;
}

.change-indicator {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-top: 4px;
}

.icon-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 2px;
}

.up-arrow {
  color: #52c41a;
}

.down-arrow {
  color: #f5222d;
}

.no-change {
  color: #d9d9d9;
}

.change-value {
  font-size: 12px;
}

.increase {
  color: #52c41a;
}

.decrease {
  color: #f5222d;
}

.no-change {
  color: #d9d9d9;
}

.progress-bar-container {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: rgba(255, 255, 255, 0.1);
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, rgba(30, 177, 252, 0.7), #1eb1fc);
  transition: width 0.5s ease;
}

/* 动画效果 */
.flip-list-move {
  transition: transform 0.5s;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 自定义滚动条 */
.ranking-list::-webkit-scrollbar {
  width: 4px;
}

.ranking-list::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

.ranking-list::-webkit-scrollbar-thumb {
  background: rgba(30, 177, 252, 0.5);
  border-radius: 2px;
}

.ranking-list::-webkit-scrollbar-thumb:hover {
  background: rgba(30, 177, 252, 0.8);
}

/* 适配Element Plus样式 */
:deep(.el-select) {
  --el-select-input-focus-border-color: #1eb1fc;
}

:deep(.el-select .el-input__wrapper) {
  background-color: rgba(0, 20, 40, 0.5);
  border: 1px solid rgba(30, 177, 252, 0.3);
}

:deep(.el-select .el-input__inner) {
  color: #fff;
}

:deep(.el-select .el-input .el-select__caret) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.el-select-dropdown) {
  background-color: rgba(0, 20, 40, 0.9);
  border: 1px solid rgba(30, 177, 252, 0.3);
}

:deep(.el-select-dropdown__item) {
  color: #fff;
}

:deep(.el-select-dropdown__item.hover) {
  background-color: rgba(30, 177, 252, 0.2);
}

:deep(.el-select-dropdown__item.selected) {
  color: #1eb1fc;
  font-weight: bold;
}
</style>
